package com.argrace.smart.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.view.View;

import com.argrace.smart.model.LocalDb_AnJianTable;
import com.argrace.smart.model.LocalDb_DeviceNameAndRoomNameTable;
import com.argrace.smart.model.LocalDb_DeviceSyncTable;
import com.argrace.smart.model.LocalDb_QingJingTable;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.model.LocalDb_RoomNameTable;
import com.argrace.smart.model.LocalDb_RuoQiDeviceTable;

import org.litepal.crud.DataSupport;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by argrace_dev_1 on 2018/3/8.
 */

public class XmlUtils {
    public static final String FileName = "Argrace";
    public static String GEN_PATH;

    public static void savexml() {
        try {
            File file = new File(GEN_PATH,
                    "argrace_db.xml");
            if (!file.exists()) {
                Log.i("info", "是否创建了新文件" + file.createNewFile());
            }
            FileOutputStream fos = new FileOutputStream(file);
            // 获得一个序列化工具
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fos, "utf-8");
            // 设置文件头
            serializer.startDocument("utf-8", true);
            serializer.startTag(null, "argrace_db");
            //查询所有表数据
            List<LocalDb_AnJianTable> anJianLists = DataSupport.findAll(LocalDb_AnJianTable.class);
            List<LocalDb_DeviceNameAndRoomNameTable> deviceNameAndRoomNameLists = DataSupport.findAll(LocalDb_DeviceNameAndRoomNameTable.class);
            List<LocalDb_QingJing_DeviceTable> qingJing_DeviceLists = DataSupport.findAll(LocalDb_QingJing_DeviceTable.class);
            List<LocalDb_QingJingTable> qingJingLists = DataSupport.findAll(LocalDb_QingJingTable.class);
            List<LocalDb_RelationDeviceTable> relationDeviceLists = DataSupport.findAll(LocalDb_RelationDeviceTable.class);
            List<LocalDb_RoomNameTable> roomNameLists = DataSupport.findAll(LocalDb_RoomNameTable.class);
            List<LocalDb_RuoQiDeviceTable> ruoQiDeviceLists = DataSupport.findAll(LocalDb_RuoQiDeviceTable.class);
            List<LocalDb_DeviceSyncTable> syncDeviceLists = DataSupport.findAll(LocalDb_DeviceSyncTable.class);
            //放入文件
            if (anJianLists != null && anJianLists.size() != 0) {
//                for (int i = 0; i < anJianLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_AnJianTable");
//                    serializer.attribute(null, "id", String.valueOf(anJianLists.get(i).getId()));
//                    putEntity("uuid", anJianLists.get(i).getUuid(), serializer);
//                    putEntity("key", anJianLists.get(i).getKey(), serializer);
//                    putEntity("QingJingTable_id", String.valueOf(anJianLists.get(i).getQingJingTable_id()), serializer);
//                    serializer.endTag(null, "LocalDb_AnJianTable");
//                }
            }
            if (syncDeviceLists != null && syncDeviceLists.size() != 0) {
                for (int i = 0; i < syncDeviceLists.size(); i++) {
                    serializer.startTag(null, "LocalDb_DeviceSyncTable");
                    serializer.attribute(null, "id", String.valueOf(syncDeviceLists.get(i).getId()));
                    putEntity("zhusheibeiuuid", syncDeviceLists.get(i).getZhusheibeiuuid(), serializer);
                    putEntity("fushebeiuuid", syncDeviceLists.get(i).getFushebeiuuid(), serializer);
                    putEntity("fushebejianzhi", syncDeviceLists.get(i).getFushebejianzhi(), serializer);
                    putEntity("zhushebeijianzhi", syncDeviceLists.get(i).getZhushebeijianzhi(), serializer);
                    serializer.endTag(null, "LocalDb_DeviceSyncTable");
                }
            }
            if (deviceNameAndRoomNameLists != null && deviceNameAndRoomNameLists.size() != 0) {
//                for (int i = 0; i < deviceNameAndRoomNameLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_DeviceNameAndRoomNameTable");
//                    serializer.attribute(null, "id", String.valueOf(deviceNameAndRoomNameLists.get(i).getId()));
//                    putEntity("uuid", deviceNameAndRoomNameLists.get(i).getUuid(), serializer);
//                    putEntity("nickName", deviceNameAndRoomNameLists.get(i).getNickName(), serializer);
//                    putEntity("roomName", deviceNameAndRoomNameLists.get(i).getRoomName(), serializer);
//                    putEntity("property", deviceNameAndRoomNameLists.get(i).getProperty(), serializer);
//                    putEntity("shortModel", deviceNameAndRoomNameLists.get(i).getShortModel(), serializer);
//                    putEntity("model", deviceNameAndRoomNameLists.get(i).getModel(), serializer);
//                    putEntity("deviceKey", deviceNameAndRoomNameLists.get(i).getDeviceKey(), serializer);
//                    putEntity("switch_state", deviceNameAndRoomNameLists.get(i).getSwitch_state(), serializer);
//                    serializer.endTag(null, "LocalDb_DeviceNameAndRoomNameTable");
//                }
            }
            if (qingJing_DeviceLists != null && qingJing_DeviceLists.size() != 0) {
//                for (int i = 0; i < qingJing_DeviceLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_QingJing_DeviceTable");
//                    serializer.attribute(null, "id", String.valueOf(qingJing_DeviceLists.get(i).getId()));
//                    putEntity("uuid", qingJing_DeviceLists.get(i).getUuid(), serializer);
//                    putEntity("img", qingJing_DeviceLists.get(i).getImg(), serializer);
//                    putEntity("name", qingJing_DeviceLists.get(i).getName(), serializer);
//                    putEntity("shortmodel", qingJing_DeviceLists.get(i).getShortmodel(), serializer);
//                    putEntity("model", qingJing_DeviceLists.get(i).getModel(), serializer);
//                    putEntity("LocalDb_DeviceTable_deviceId", qingJing_DeviceLists.get(i).getLocalDb_DeviceTable_deviceId(), serializer);
//                    putEntity("json_params", qingJing_DeviceLists.get(i).getJson_params(), serializer);
//                    serializer.endTag(null, "LocalDb_QingJing_DeviceTable");
//                }
            }
            if (qingJingLists != null && qingJingLists.size() != 0) {
//                for (int i = 0; i < qingJingLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_QingJingTable");
//                    serializer.attribute(null, "id", String.valueOf(qingJingLists.get(i).getId()));
//                    putEntity("roomName", qingJingLists.get(i).getRoomName(), serializer);
//                    putEntity("deviceId", qingJingLists.get(i).getDeviceId(), serializer);
//                    putEntity("name", qingJingLists.get(i).getName(), serializer);
//                    serializer.endTag(null, "LocalDb_QingJingTable");
//                }
            }
            if (relationDeviceLists != null && relationDeviceLists.size() != 0) {
//                for (int i = 0; i < relationDeviceLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_RelationDeviceTable");
//                    serializer.attribute(null, "id", String.valueOf(relationDeviceLists.get(i).getId()));
//                    putEntity("uuid", relationDeviceLists.get(i).getUuid(), serializer);
//                    putEntity("QingJingTable_id", relationDeviceLists.get(i).getQingJingTable_id(), serializer);
//                    putEntity("Trigger_condition", relationDeviceLists.get(i).getTrigger_condition(), serializer);
//                    putEntity("model", relationDeviceLists.get(i).getModel(), serializer);
//                    serializer.endTag(null, "LocalDb_RelationDeviceTable");
//                }
            }
            if (roomNameLists != null && roomNameLists.size() != 0) {
//                for (int i = 0; i < roomNameLists.size(); i++) {
//                    serializer.startTag(null, "LocalDb_RoomNameTable");
//                    serializer.attribute(null, "id", String.valueOf(roomNameLists.get(i).getId()));
//                    putEntity("roomName", roomNameLists.get(i).getRoomName(), serializer);
//                    serializer.endTag(null, "LocalDb_RoomNameTable");
//                }
            }
            if (ruoQiDeviceLists != null && ruoQiDeviceLists.size() != 0) {
                for (int i = 0; i < ruoQiDeviceLists.size(); i++) {
                    serializer.startTag(null, "LocalDb_RuoQiDeviceTable");
                    serializer.attribute(null, "id", String.valueOf(ruoQiDeviceLists.get(i).getId()));
                    putEntity("uuid", ruoQiDeviceLists.get(i).getUuid(), serializer);
                    putEntity("is_add", String.valueOf(ruoQiDeviceLists.get(i).isIs_add()), serializer);
                    putEntity("keybord", ruoQiDeviceLists.get(i).getKeybord(), serializer);
                    putEntity("device_json", ruoQiDeviceLists.get(i).getDevice_json(), serializer);
                    putEntity("name", ruoQiDeviceLists.get(i).getName(), serializer);
                    serializer.endTag(null, "LocalDb_RuoQiDeviceTable");
                }
            }
            serializer.endTag(null, "argrace_db");
            serializer.endDocument();
            fos.close();
            Log.i("info", "---------");
        } catch (Exception e) {
            Log.i("info", "*************" + e.toString());
            e.printStackTrace();
        }
    }

    public static void readxml(Context c) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(c.getAssets().open("My_db.xml"));
            Element element = document.getDocumentElement();
            NodeList nodeList_DeviceNameAndRoomName = element.getElementsByTagName("LocalDb_DeviceNameAndRoomNameTable");
            for (int i = 0; i < nodeList_DeviceNameAndRoomName.getLength(); i++) {
                Element lan = (Element) nodeList_DeviceNameAndRoomName.item(i);
                LocalDb_DeviceNameAndRoomNameTable entity = new LocalDb_DeviceNameAndRoomNameTable();
                try {
                    entity.setId(Integer.parseInt(lan.getAttribute("id")));
                    entity.setUuid(lan.getElementsByTagName("uuid").item(0).getTextContent());
                    entity.setNickName(lan.getElementsByTagName("nickName").item(0).getTextContent());
                    entity.setModel(lan.getElementsByTagName("model").item(0).getTextContent());
                    entity.setDeviceKey(lan.getElementsByTagName("deviceKey").item(0).getTextContent());
                    entity.setProperty(lan.getElementsByTagName("property").item(0).getTextContent());
                    entity.setRoomName(lan.getElementsByTagName("roomName").item(0).getTextContent());
                } catch (Exception e) {
                } finally {
                    int result = entity.updateAll("uuid = ? and deviceKey= ?", entity.getUuid(), entity.getDeviceKey());
                    if (result == 0) {
                        entity.save();
                    }
                }
            }
            NodeList nodeList_roomName = element.getElementsByTagName("LocalDb_RoomNameTable");
            for (int i = 0; i < nodeList_roomName.getLength(); i++) {
                Element lan = (Element) nodeList_roomName.item(i);
                LocalDb_RoomNameTable entity = new LocalDb_RoomNameTable();
                entity.setId(Integer.parseInt(lan.getAttribute("id")));
                entity.setRoomName(lan.getElementsByTagName("roomName").item(0).getTextContent());
                int result = entity.updateAll("roomName = ?", entity.getRoomName());
                if (result == 0) {
                    entity.save();
                }
            }
            NodeList nodeList_ruoqi = element.getElementsByTagName("LocalDb_RuoQiDeviceTable");
            for (int i = 0; i < nodeList_ruoqi.getLength(); i++) {
                Element lan = (Element) nodeList_ruoqi.item(i);
                LocalDb_RuoQiDeviceTable entity = new LocalDb_RuoQiDeviceTable();
                entity.setId(Integer.parseInt(lan.getAttribute("id")));
                entity.setUuid(lan.getElementsByTagName("uuid").item(0).getTextContent());
                entity.setIs_add(false);
                entity.setDevice_json(lan.getElementsByTagName("device_json").item(0).getTextContent());
                entity.setName(lan.getElementsByTagName("name").item(0).getTextContent());
                int result = entity.updateAll("uuid = ?", entity.getUuid());
                if (result == 0) {
                    entity.save();
                }
            }
            NodeList nodeList_qingJing = element.getElementsByTagName("LocalDb_QingJingTable");
            for (int i = 0; i < nodeList_qingJing.getLength(); i++) {
                Element lan = (Element) nodeList_qingJing.item(i);
                LocalDb_QingJingTable entity = new LocalDb_QingJingTable();
                try {
                    entity.setId(Integer.parseInt(lan.getAttribute("id")));
                    entity.setRoomName(lan.getElementsByTagName("roomName").item(0).getTextContent());
                    entity.setDeviceId(lan.getElementsByTagName("deviceId").item(0).getTextContent());
                    entity.setName(lan.getElementsByTagName("name").item(0).getTextContent());
                    Log.i("info", "LocalDb_QingJingTable=" + entity.getRoomName());
                } catch (Exception e) {
                    Log.i("info", "读取LocalDb_QingJingTable,uuid=" + entity.getRoomName() + "时出错");
                } finally {
                    int result = entity.updateAll("name = ?", entity.getName());
                    if (result == 0) {
                        entity.save();
                    }
                }
            }
            NodeList nodeList_syncDev = element.getElementsByTagName("LocalDb_DeviceSyncTable");
            for (int i = 0; i < nodeList_syncDev.getLength(); i++) {
                Element lan = (Element) nodeList_syncDev.item(i);
                LocalDb_DeviceSyncTable entity = new LocalDb_DeviceSyncTable();
                try {
                    entity.setId(Integer.parseInt(lan.getAttribute("id")));
                    entity.setFushebeiuuid(lan.getElementsByTagName("fushebeiuuid").item(0).getTextContent());
                    entity.setZhusheibeiuuid(lan.getElementsByTagName("zhusheibeiuuid").item(0).getTextContent());
                    entity.setFushebejianzhi(lan.getElementsByTagName("fushebejianzhi").item(0).getTextContent());
                    entity.setZhushebeijianzhi(lan.getElementsByTagName("zhushebeijianzhi").item(0).getTextContent());
                } catch (Exception e) {
                } finally {
                    int db_result = entity.updateAll("zhusheibeiuuid = ? and zhushebeijianzhi = ? ", entity.getZhusheibeiuuid(), entity.getZhushebeijianzhi());
                    if (db_result == 0) {
                        entity.save();
                    }
                }
            }
            NodeList nodeList_qingJingDevice = element.getElementsByTagName("LocalDb_QingJing_DeviceTable");
            for (int i = 0; i < nodeList_qingJingDevice.getLength(); i++) {
                Element lan = (Element) nodeList_qingJingDevice.item(i);
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                try {
                    entity.setId(Integer.parseInt(lan.getAttribute("id")));
                    entity.setUuid(lan.getElementsByTagName("uuid").item(0).getTextContent());
                    entity.setName(lan.getElementsByTagName("name").item(0).getTextContent());
                    entity.setModel(lan.getElementsByTagName("model").item(0).getTextContent());
                    entity.setLocalDb_DeviceTable_deviceId(lan.getElementsByTagName("LocalDb_DeviceTable_deviceId").item(0).getTextContent());
                    entity.setJson_params(lan.getElementsByTagName("json_params").item(0).getTextContent());
                    Log.i("info", "LocalDb_QingJing_DeviceTable=" + entity.getUuid());
                } catch (Exception e) {
                    Log.i("info", "读取uuid=" + entity.getUuid() + "时出错");
                } finally {
                    int result = entity.updateAll("uuid = ? and name = ? and LocalDb_DeviceTable_deviceId = ?", entity.getUuid(), entity.getName(), entity.getLocalDb_DeviceTable_deviceId());
                    if (result == 0) {
                        entity.save();
                    }
                }
            }
            Log.i("info", "XML读取完毕");
        } catch (Exception e) {
            Log.i("info", "转换数据的时候发现异常" + e.toString());
        }
    }

    private static void putEntity(String key, String value, XmlSerializer serializer) throws IOException {
        if (value == null) {
            return;
        }
        serializer.startTag(null, key);
        serializer.text(value);
        serializer.endTag(null, key);
    }

    private static void putEntity(String key, int value, XmlSerializer serializer) throws IOException {

        serializer.startTag(null, key);
        serializer.text(String.valueOf(value));
        serializer.endTag(null, key);
    }

    public static void initPath(Context c) {
        String genFile = isRemovableSDCardAvailable(c);
        if (genFile == null || genFile.equals("")) {
            Log.i("info", "----获取不到当前手机根目录！");
            return;
        }
        Log.i("info", "------获取得目录是" + genFile);
        File file = new File(genFile + File.separator + FileName);// 创建文件夹-压缩
        if (!file.exists()) {
            //不存在可能是华为手机
            reSetPath();
        } else {
            Log.i("info", "创建目录---" + file.mkdirs());
            GEN_PATH = file.getAbsolutePath();
            Log.i("info", "GEN_PATH是" + GEN_PATH);
        }
//        }

    }

    /**
     * 华为手机上边获取路径的方法不对，那么再次调用以下方法
     */
    public static void reSetPath() {
        try {
            GEN_PATH = Environment
                    .getExternalStorageDirectory().getPath()
                    + File.separator
                    + FileName;
            File file = new File(GEN_PATH);
            if (!file.exists()) {
                file.mkdirs();

            } else {
                Log.i("info", "获取不到此款手机的文件创建权限！");
            }

        } catch (Exception e) {
        }
    }

    public static String isRemovableSDCardAvailable(Context context) {
        final String FLAG = "mnt";
        final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE");
        final String EXTERNAL_STORAGE_DOCOMO = System.getenv("EXTERNAL_STORAGE_DOCOMO");
        final String EXTERNAL_SDCARD_STORAGE = System.getenv("EXTERNAL_SDCARD_STORAGE");
        final String EXTERNAL_SD_STORAGE = System.getenv("EXTERNAL_SD_STORAGE");
        final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");

        Map<Integer, String> listEnvironmentVariableStoreSDCardRootDirectory = new HashMap<Integer, String>();
        listEnvironmentVariableStoreSDCardRootDirectory.put(0, SECONDARY_STORAGE);
        listEnvironmentVariableStoreSDCardRootDirectory.put(1, EXTERNAL_STORAGE_DOCOMO);
        listEnvironmentVariableStoreSDCardRootDirectory.put(2, EXTERNAL_SDCARD_STORAGE);
        listEnvironmentVariableStoreSDCardRootDirectory.put(3, EXTERNAL_SD_STORAGE);
        listEnvironmentVariableStoreSDCardRootDirectory.put(4, EXTERNAL_STORAGE);

        File externalStorageList[] = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            externalStorageList = context.getExternalFilesDirs(null);
        }
        String directory = null;
        int size = listEnvironmentVariableStoreSDCardRootDirectory.size();
        for (int i = 0; i < size; i++) {
            if (externalStorageList != null && externalStorageList.length > 1 && externalStorageList[1] != null)
                directory = externalStorageList[1].getAbsolutePath();
            else
                directory = listEnvironmentVariableStoreSDCardRootDirectory.get(i);
            if (directory != null) {
                return directory;
            }

        }
        return null;
    }

}
